package com.wuwangfu.partition;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

/**
 * @Author jcshen
 * @Date 2023-02-23
 * @PackageName:com.wuwangfu.partition
 * @ClassName: Rebalance
 * @Description: 轮询分区，使用轮询的方式将数据发送到下游的substask，会跨网络运行]
 * @Version 1.0.0
 *
 */
public class Rebalance {
    public static void main(String[] args) throws Exception {
        Configuration config = new Configuration();
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(config);
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<String> maped = line.map(new RichMapFunction<String, String>() {
            @Override
            public String map(String value) throws Exception {
                int subTask = getRuntimeContext().getIndexOfThisSubtask();
                return value + " : " + subTask;
            }
        });

        //使用轮询的方式将数据发送到下游的substask
        DataStream<String> rebalanced = maped.rebalance();

        rebalanced.addSink(new RichSinkFunction<String>() {

            @Override
            public void invoke(String value, Context context) throws Exception {
                int subTask = getRuntimeContext().getIndexOfThisSubtask();
                System.out.println(value + "->" + subTask);
            }
        });

        env.execute();
    }
}
